package com.zzyl.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.AlertDataHandleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.User;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.service.AlertDataService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.AlertDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description AlertDataServiceImpl
 * @Author Lwj
 * @Date 2024-09-15-17:06
 */
@Service
public class AlertDataServiceImpl implements AlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 分页查询报警数据
     *
     * @param pageNum
     * @param pageSize
     * @param deviceName
     * @param endTime
     * @param id
     * @param startTime
     * @param status
     * @return
     */
    @Override
    public PageResponse<AlertDataVo> pageAlertData(Long pageNum, Long pageSize, String deviceName, Long endTime, Long id, Long startTime, Long status) {
        //使用PageHelper分页工具
        PageHelper.startPage(Math.toIntExact(pageNum), Math.toIntExact(pageSize));
        //查询数据库数据
        Page<AlertDataVo> alertDataVoPage = alertDataMapper.page(deviceName, endTime, id, startTime, status);
        return PageResponse.of(alertDataVoPage, AlertDataVo.class);
    }

    /**
     * 处理设备报警数据
     *
     * @param id
     * @param alertDataHandleDto
     */
    @Override
    public void handleAlertData(Long id, AlertDataHandleDto alertDataHandleDto) {
        AlertData alertData = alertDataMapper.selectByPrimaryKey(id);

        //从当前线程中获取用户数据，更新报警数据
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);
        alertDataMapper.handleAlertData(id, alertDataHandleDto.getProcessingResult(), alertDataHandleDto.getProcessingTime(), user.getRealName(), user.getId(),alertData.getIotId());

        String iotId = alertData.getIotId();
        Long userId = user.getId();
        String realName = user.getRealName();

        alertDataMapper.updateStatus(iotId,userId,realName,alertDataHandleDto.getProcessingResult(), alertDataHandleDto.getProcessingTime());
    }
}
